package xiaohong.sort;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class MergeSortDemo {

    public static void main(String[] args) {
        int[] nums = new int[10000000];
        for (int i = 0; i < 10000000; i++) {
            nums[i] = (int)(Math.random() * 100000000);
        }
//        System.out.println("排序前" + Arrays.toString(nums));
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println( "排序之前时间" +formatter.format(date));
        mergeSort(nums , 0 , nums.length - 1 , new int[nums.length] );
        Date date1 = new Date();
        System.out.println( "排序之后时间" +formatter.format(date1));
//        System.out.println("排序后" + Arrays.toString(nums));
    }

    public static void mergeSort(int[] nums , int left, int right, int[] res) {
        if (left < right) {
            // 中间索引
            int mid = (left + right) / 2;
            // 香左递归
            mergeSort(nums, left, mid, res);
            // 向右递归
            mergeSort(nums, mid + 1, right, res);
            // 合并
            merge(nums, left, mid, right ,res);
        }
    }

    public static void merge(int[] nums, int l,  int mid ,int r , int[] res) {
        int left = l ;
        int right = mid +  1;
        int t = 0;
        while (left <= mid && right <= r) {
            if (nums[left]< nums[right]) {
                res[t] = nums[left];
                left ++;
                t ++ ;
            }else {
                res[t] = nums[right];
                right++;
                t ++ ;
            }
        }

        while (left <= mid) {
            res[t] = nums[left];
            left++;
            t ++ ;
        }
        while (right <= r) {
            res[t] = nums[right];
            right++;
            t ++ ;
        }
        int tmp = 0;
        int tempLeft = l;
        while (tempLeft <= r) {
            nums[tempLeft] = res[tmp];
            tmp ++ ;
            tempLeft ++;
        }
    }


}
